#include"myls.h"

int get_file_type(char *sourcePath)
{
	struct stat info;

	if(lstat(sourcePath, &info) == 0)
	{
		if (S_ISREG(info.st_mode))
		{
		return 1;
		}else if (S_ISDIR(info.st_mode))
			return 2;
		else
			return -1;
	}else
	{
		perror("stat");
		return 0;
	}
}

void create_mycp_thread(char* sourcePath,char *targetPath)
{
	pthread_t tid2;

	Msgcp msgcp;
	msgcp.source = sourcePath;
	msgcp.target = targetPath;

	if (pthread_create(&tid2, NULL, (void *)&thread_mycp, &msgcp) != 0) {
		printf("thread mycp create fail\n");
		return ;
	}

	if (pthread_join(tid2, NULL) != 0)  //非并发执行
	{
		printf("cannot join with thread mycp\n");
		return ;
	}

}

void do_ls(char *currentPath,char *targetPath)
{

	char *sourcePath = (char *)malloc(MAX_FILE_LIST * sizeof(char));
	char *nTargetPath = (char *)malloc(MAX_FILE_LIST * sizeof(char));

	if(targetPath == NULL)
	{
		targetPath = TARGET_FILE_PATH;
	}
	DIR *currentDir = opendir(currentPath);	
	struct dirent *entry;

	if(currentDir  == NULL )
	{		
		perror("opendir()");
		return ;
	}


	while(1)
	{
        	if((entry = readdir(currentDir)) == NULL)
       	 	{
			if(errno)
			{
                	perror("readdir()");
                	return ;
            		}
            		break;
        	}
		if(entry->d_name[0] != '.')
		{
			strcpy(sourcePath, currentPath);
			strcat(sourcePath, "/");
			strcat(sourcePath, entry->d_name);

			strcpy(nTargetPath , targetPath);
			strcat(nTargetPath, "/");
			strcat(nTargetPath, entry->d_name);
			int fileType = get_file_type(sourcePath);

			if (fileType == 1) //非目录文件
			{
				create_mycp_thread(sourcePath, nTargetPath);
			}else if (fileType == 2) //目录文件
			{
				if(mkdir(nTargetPath, S_IRWXU) == -1)
				{
					perror("mkdir()");
					return ;
				}
				create_myls_thread(sourcePath, nTargetPath);
			}
		}
	}
	if (closedir(currentDir) == -1)
	{
		err_exit("closedir");
	}

	free(sourcePath);
	free(nTargetPath); 
}

void *thread_myls(void *arg)
{
	Msgcp *msgls = (Msgcp *)arg;
	char *sourcePath = msgls->source;
	char *targetPath = msgls->target;
	do_ls(sourcePath, targetPath);
}

void *thread_mycp(void *arg)
{
	//pthread_detach(pthread_self()); //并发执行
	Msgcp *msgcp = (Msgcp *)arg;
	char *sourcePath = msgcp->source;
	char *targetPath = msgcp->target;
	mycp(sourcePath, targetPath);
}

void create_myls_thread(char *sourcePath, char *targetPath)
{
	pthread_t tid;
	Msgcp msgls;
	msgls.source = sourcePath;
	msgls.target = targetPath;

	if (pthread_create(&tid,NULL,(void *)&thread_myls,&msgls) != 0) 
	{
		printf("thread myls create fail\n");
		return ;
	}
	if (pthread_join(tid, NULL) != 0) 
	{
		printf("cannot join with thread myls\n");
		return ;
	}

}
